home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / python-support / python-rdflib / rdflib / Graph.py < prev    next >
Encoding:
Python Source  |  2007-04-04  |  42.0 KB  |  1,197 lines

  1. from __future__ import generators
  2.  
  3. __doc__="""
  4. Instanciating Graphs with default store (IOMemory) and default identifier (a BNode):
  5.  
  6.     >>> g=Graph()
  7.     >>> g.store.__class__
  8.     <class 'rdflib.store.IOMemory.IOMemory'>
  9.     >>> g.identifier.__class__
  10.     <class 'rdflib.BNode.BNode'>
  11.  
  12. Instanciating Graphs with a specific kind of store (IOMemory) and a default identifier (a BNode):
  13.  
  14. Other store kinds: Sleepycat, MySQL, ZODB, SQLite
  15.  
  16.     >>> store = plugin.get('IOMemory',Store)()
  17.     >>> store.__class__.__name__
  18.     'IOMemory'
  19.     >>> graph = Graph(store)
  20.     >>> graph.store.__class__
  21.     <class 'rdflib.store.IOMemory.IOMemory'>
  22.  
  23. Instanciating Graphs with Sleepycat store and an identifier - <http://rdflib.net>:
  24.  
  25.     >>> g=Graph('Sleepycat',URIRef("http://rdflib.net"))
  26.     >>> g.identifier
  27.     rdflib.URIRef('http://rdflib.net')
  28.     >>> str(g)
  29.     "<http://rdflib.net> a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'Sleepycat']."
  30.  
  31. Creating a ConjunctiveGraph - The top level container for all named Graphs in a 'database':
  32.  
  33.     >>> g=ConjunctiveGraph()
  34.     >>> str(g.default_context)
  35.     "[a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'IOMemory']]."
  36.  
  37. Adding / removing reified triples to Graph and iterating over it directly or via triple pattern:
  38.     
  39.     >>> g=Graph('IOMemory')
  40.     >>> statementId = BNode()
  41.     >>> print len(g)
  42.     0
  43.     >>> g.add((statementId,RDF.type,RDF.Statement))
  44.     >>> g.add((statementId,RDF.subject,URIRef('http://rdflib.net/store/ConjunctiveGraph')))
  45.     >>> g.add((statementId,RDF.predicate,RDFS.label))
  46.     >>> g.add((statementId,RDF.object,Literal("Conjunctive Graph")))
  47.     >>> print len(g)
  48.     4
  49.     >>> for s,p,o in g:  print type(s)
  50.     ...
  51.     <class 'rdflib.BNode.BNode'>
  52.     <class 'rdflib.BNode.BNode'>
  53.     <class 'rdflib.BNode.BNode'>
  54.     <class 'rdflib.BNode.BNode'>
  55.     
  56.     >>> for s,p,o in g.triples((None,RDF.object,None)):  print o
  57.     ...
  58.     Conjunctive Graph
  59.     >>> g.remove((statementId,RDF.type,RDF.Statement))
  60.     >>> print len(g)
  61.     3
  62.  
  63. None terms in calls to triple can be thought of as 'open variables'  
  64.  
  65. Graph Aggregation - ConjunctiveGraphs and ReadOnlyGraphAggregate within the same store:
  66.     
  67.     >>> store = plugin.get('IOMemory',Store)()
  68.     >>> g1 = Graph(store)
  69.     >>> g2 = Graph(store)
  70.     >>> g3 = Graph(store)
  71.     >>> stmt1 = BNode()
  72.     >>> stmt2 = BNode()
  73.     >>> stmt3 = BNode()
  74.     >>> g1.add((stmt1,RDF.type,RDF.Statement))
  75.     >>> g1.add((stmt1,RDF.subject,URIRef('http://rdflib.net/store/ConjunctiveGraph')))
  76.     >>> g1.add((stmt1,RDF.predicate,RDFS.label))
  77.     >>> g1.add((stmt1,RDF.object,Literal("Conjunctive Graph")))
  78.     >>> g2.add((stmt2,RDF.type,RDF.Statement))
  79.     >>> g2.add((stmt2,RDF.subject,URIRef('http://rdflib.net/store/ConjunctiveGraph')))
  80.     >>> g2.add((stmt2,RDF.predicate,RDF.type))
  81.     >>> g2.add((stmt2,RDF.object,RDFS.Class))
  82.     >>> g3.add((stmt3,RDF.type,RDF.Statement))
  83.     >>> g3.add((stmt3,RDF.subject,URIRef('http://rdflib.net/store/ConjunctiveGraph')))
  84.     >>> g3.add((stmt3,RDF.predicate,RDFS.comment))
  85.     >>> g3.add((stmt3,RDF.object,Literal("The top-level aggregate graph - The sum of all named graphs within a Store")))
  86.     >>> len(list(ConjunctiveGraph(store).subjects(RDF.type,RDF.Statement)))
  87.     3
  88.     >>> len(list(ReadOnlyGraphAggregate([g1,g2]).subjects(RDF.type,RDF.Statement)))
  89.     2
  90.  
  91. ConjunctiveGraphs have a 'quads' method which returns quads instead of triples, where the fourth item
  92. is the Graph (or subclass thereof) instance in which the triple was asserted:
  93.     
  94.     >>> from sets import Set    
  95.     >>> uniqueGraphNames = Set([graph.identifier for s,p,o,graph in ConjunctiveGraph(store).quads((None,RDF.predicate,None))])
  96.     >>> len(uniqueGraphNames)
  97.     3
  98.     >>> unionGraph = ReadOnlyGraphAggregate([g1,g2])
  99.     >>> uniqueGraphNames = Set([graph.identifier for s,p,o,graph in unionGraph.quads((None,RDF.predicate,None))])
  100.     >>> len(uniqueGraphNames)
  101.     2
  102.      
  103. Parsing N3 from StringIO
  104.  
  105.     >>> g2=Graph()
  106.     >>> src = \"\"\"
  107.     ... @prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
  108.     ... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
  109.     ... [ a rdf:Statement ;
  110.     ...   rdf:subject <http://rdflib.net/store#ConjunctiveGraph>;
  111.     ...   rdf:predicate rdfs:label;
  112.     ...   rdf:object "Conjunctive Graph" ] \"\"\"
  113.     >>> g2=g2.parse(StringIO(src),format='n3')
  114.     >>> print len(g2)
  115.     4
  116.  
  117. Using Namespace class:
  118.  
  119.     >>> RDFLib = Namespace('http://rdflib.net')
  120.     >>> RDFLib.ConjunctiveGraph
  121.     rdflib.URIRef('http://rdflib.netConjunctiveGraph')
  122.     >>> RDFLib['Graph']
  123.     rdflib.URIRef('http://rdflib.netGraph')
  124.  
  125. SPARQL Queries
  126.  
  127.     >>> print len(g)
  128.     3
  129.     >>> q = \'\'\'
  130.     ... PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT ?pred WHERE { ?stmt rdf:predicate ?pred. }
  131.     ... \'\'\'   
  132.     >>> for pred in g.query(q):  print pred
  133.     (rdflib.URIRef('http://www.w3.org/2000/01/rdf-schema#label'),)
  134.  
  135. SPARQL Queries with namespace bindings as argument
  136.  
  137.     >>> nsMap = {u"rdf":RDF.RDFNS}
  138.     >>> for pred in g.query("SELECT ?pred WHERE { ?stmt rdf:predicate ?pred. }", initNs=nsMap): print pred
  139.     (rdflib.URIRef('http://www.w3.org/2000/01/rdf-schema#label'),)
  140.  
  141. Parameterized SPARQL Queries
  142.  
  143.     >>> top = { Variable("?term") : RDF.predicate }
  144.     >>> for pred in g.query("SELECT ?pred WHERE { ?stmt ?term ?pred. }", initBindings=top): print pred
  145.     (rdflib.URIRef('http://www.w3.org/2000/01/rdf-schema#label'),)
  146.  
  147. """
  148.  
  149.  
  150. from cStringIO import StringIO
  151. from rdflib import URIRef, BNode, Namespace, Literal, Variable
  152. from rdflib import RDF, RDFS
  153.  
  154. from rdflib.Node import Node
  155.  
  156. from rdflib import plugin, exceptions
  157.  
  158. from rdflib.store import Store
  159.  
  160. from rdflib.syntax.serializer import Serializer
  161. from rdflib.syntax.parsers import Parser
  162. from rdflib.syntax.NamespaceManager import NamespaceManager
  163. from rdflib import sparql
  164. from rdflib.QueryResult import QueryResult
  165. from rdflib.URLInputSource import URLInputSource
  166.  
  167. from xml.sax.xmlreader import InputSource
  168. from xml.sax.saxutils import prepare_input_source
  169.  
  170. import logging
  171. _logger = logging.getLogger("rdflib.Graph")
  172.  
  173. #import md5
  174. import random
  175. import warnings
  176.  
  177. try:
  178.     from hashlib import md5
  179. except ImportError:
  180.     from md5 import md5    
  181.  
  182. class Graph(Node):
  183.     """An RDF Graph
  184.  
  185.     The constructor accepts one argument, the 'store'
  186.     that will be used to store the graph data (see the 'store'
  187.     package for stores currently shipped with rdflib).
  188.  
  189.     Stores can be context-aware or unaware.  Unaware stores take up
  190.     (some) less space but cannot support features that require
  191.     context, such as true merging/demerging of sub-graphs and
  192.     provenance.
  193.  
  194.     The Graph constructor can take an identifier which identifies the Graph
  195.     by name.  If none is given, the graph is assigned a BNode for it's identifier.
  196.     For more on named graphs, see: http://www.w3.org/2004/03/trix/
  197.  
  198.     Ontology for __str__ provenance terms:
  199.  
  200.     @prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
  201.     @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
  202.     @prefix : <http://rdflib.net/store#> .
  203.     @prefix rdfg: <http://www.w3.org/2004/03/trix/rdfg-1/>.
  204.     @prefix owl: <http://www.w3.org/2002/07/owl#>.
  205.     @prefix log: <http://www.w3.org/2000/10/swap/log#>.
  206.     @prefix xsd: <http://www.w3.org/2001/XMLSchema#>.
  207.  
  208.     :Store a owl:Class;
  209.         rdfs:subClassOf <http://xmlns.com/wordnet/1.6/Electronic_database>;
  210.         rdfs:subClassOf
  211.             [a owl:Restriction;
  212.              owl:onProperty rdfs:label;
  213.              owl:allValuesFrom [a owl:DataRange;
  214.                                 owl:oneOf ("IOMemory"
  215.                                            "Sleepcat"
  216.                                            "MySQL"
  217.                                            "Redland"
  218.                                            "REGEXMatching"
  219.                                            "ZODB"
  220.                                            "AuditableStorage"
  221.                                            "Memory")]
  222.             ].
  223.  
  224.     :ConjunctiveGraph a owl:Class;
  225.         rdfs:subClassOf rdfg:Graph;
  226.         rdfs:label "The top-level graph within the store - the union of all the Graphs within."
  227.         rdfs:seeAlso <http://rdflib.net/rdf_store/#ConjunctiveGraph>.
  228.  
  229.     :DefaultGraph a owl:Class;
  230.         rdfs:subClassOf rdfg:Graph;
  231.         rdfs:label "The 'default' subgraph of a conjunctive graph".
  232.  
  233.  
  234.     :identifier a owl:Datatypeproperty;
  235.         rdfs:label "The store-associated identifier of the formula. ".
  236.         rdfs:domain log:Formula
  237.         rdfs:range xsd:anyURI;
  238.  
  239.     :storage a owl:ObjectProperty;
  240.         rdfs:domain [
  241.             a owl:Class;
  242.             owl:unionOf (log:Formula rdfg:Graph :ConjunctiveGraph)
  243.         ];
  244.         rdfs:range :Store.
  245.  
  246.     :default_context a owl:FunctionalProperty;
  247.         rdfs:label "The default context for a conjunctive graph";
  248.         rdfs:domain :ConjunctiveGraph;
  249.         rdfs:range :DefaultGraph.
  250.  
  251.  
  252.     {?cg a :ConjunctiveGraph;:storage ?store}
  253.       => {?cg owl:sameAs ?store}.
  254.  
  255.     {?subGraph rdfg:subGraphOf ?cg;a :DefaultGraph}
  256.       => {?cg a :ConjunctiveGraph;:default_context ?subGraphOf} .
  257.     """
  258.  
  259.     def __init__(self, store='default', identifier=None,
  260.                  namespace_manager=None):
  261.         super(Graph, self).__init__()
  262.         self.__identifier = identifier or BNode()
  263.         if not isinstance(store, Store):
  264.             # TODO: error handling
  265.             self.__store = store = plugin.get(store, Store)()
  266.         else:
  267.             self.__store = store
  268.         self.__namespace_manager = namespace_manager
  269.         self.context_aware = False
  270.         self.formula_aware = False
  271.  
  272.     def __get_store(self):
  273.         return self.__store
  274.     store = property(__get_store)
  275.  
  276.     def __get_identifier(self):
  277.         return self.__identifier
  278.     identifier = property(__get_identifier)
  279.  
  280.     def _get_namespace_manager(self):
  281.         if self.__namespace_manager is None:
  282.             self.__namespace_manager = NamespaceManager(self)
  283.         return self.__namespace_manager
  284.  
  285.     def _set_namespace_manager(self, nm):
  286.         self.__namespace_manager = nm
  287.     namespace_manager = property(_get_namespace_manager, _set_namespace_manager)
  288.  
  289.     def __repr__(self):
  290.         return "<Graph identifier=%s (%s)>" % (self.identifier, type(self))
  291.  
  292.     def __str__(self):
  293.         if isinstance(self.identifier,URIRef):
  294.             return "%s a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label '%s']."%(self.identifier.n3(),self.store.__class__.__name__)
  295.         else:
  296.             return "[a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label '%s']]."%(self.store.__class__.__name__)
  297.  
  298.     def destroy(self, configuration):
  299.         """Destroy the store identified by `configuration` if supported"""
  300.         self.__store.destroy(configuration)
  301.  
  302.     #Transactional interfaces (optional)
  303.     def commit(self):
  304.         """Commits active transactions"""
  305.         self.__store.commit()
  306.  
  307.     def rollback(self):
  308.         """Rollback active transactions"""
  309.         self.__store.rollback()
  310.  
  311.     def open(self, configuration, create=False):
  312.         """Open the graph store
  313.  
  314.         Might be necessary for stores that require opening a connection to a
  315.         database or acquiring some resource.
  316.         """
  317.         return self.__store.open(configuration, create)
  318.  
  319.     def close(self, commit_pending_transaction=False):
  320.         """Close the graph store
  321.  
  322.         Might be necessary for stores that require closing a connection to a
  323.         database or releasing some resource.
  324.         """
  325.         self.__store.close(commit_pending_transaction=commit_pending_transaction)
  326.  
  327.     def add(self, (s, p, o)):
  328.         """Add a triple with self as context"""
  329.         self.__store.add((s, p, o), self, quoted=False)
  330.  
  331.     def addN(self, quads):
  332.         """Add a sequence of triple with context"""
  333.         self.__store.addN([(s, p, o, c) for s, p, o, c in quads
  334.                                         if isinstance(c, Graph)
  335.                                         and c.identifier is self.identifier])
  336.  
  337.     def remove(self, (s, p, o)):
  338.         """Remove a triple from the graph
  339.  
  340.         If the triple does not provide a context attribute, removes the triple
  341.         from all contexts.
  342.         """
  343.         self.__store.remove((s, p, o), context=self)
  344.  
  345.     def triples(self, (s, p, o)):
  346.         """Generator over the triple store
  347.  
  348.         Returns triples that match the given triple pattern. If triple pattern
  349.         does not provide a context, all contexts will be searched.
  350.         """
  351.         for (s, p, o), cg in self.__store.triples((s, p, o), context=self):
  352.             yield (s, p, o)
  353.  
  354.     def __len__(self):
  355.         """Returns the number of triples in the graph
  356.  
  357.         If context is specified then the number of triples in the context is
  358.         returned instead.
  359.         """
  360.         return self.__store.__len__(context=self)
  361.  
  362.     def __iter__(self):
  363.         """Iterates over all triples in the store"""
  364.         return self.triples((None, None, None))
  365.  
  366.     def __contains__(self, triple):
  367.         """Support for 'triple in graph' syntax"""
  368.         for triple in self.triples(triple):
  369.             return 1
  370.         return 0
  371.  
  372.     def __hash__(self):
  373.         return hash(self.identifier)
  374.  
  375.     def md5_term_hash(self):
  376.         d = md5(str(self.identifier))
  377.         d.update("G")
  378.         return d.hexdigest()
  379.  
  380.     def __cmp__(self, other):
  381.         if other is None:
  382.             return -1
  383.         elif isinstance(other, Graph):
  384.             return cmp(self.identifier, other.identifier)
  385.         else:
  386.             #Note if None is considered equivalent to owl:Nothing
  387.             #Then perhaps a graph with length 0 should be considered
  388.             #equivalent to None (if compared to it)?
  389.             return 1
  390.  
  391.     def __iadd__(self, other):
  392.         """Add all triples in Graph other to Graph"""
  393.         for triple in other:
  394.             self.add(triple)
  395.         return self
  396.  
  397.     def __isub__(self, other):
  398.         """Subtract all triples in Graph other from Graph"""
  399.         for triple in other:
  400.             self.remove(triple)
  401.         return self
  402.  
  403.     def __add__(self,other) :
  404.         """Set theoretical union"""
  405.         retval = Graph()
  406.         for x in self.graph:
  407.             retval.add(x)
  408.         for y in other.graph:
  409.             retval.add(y)
  410.         return retval
  411.  
  412.     def __mul__(self,other) :
  413.         """Set theoretical intersection"""
  414.         retval = Graph()
  415.         for x in other.graph:
  416.             if x in self.graph: 
  417.                 retval.add(x)
  418.         return retval
  419.  
  420.     def __sub__(self,other) :
  421.         """Set theoretical difference"""
  422.         retval = Graph()
  423.         for x in self.graph:
  424.             if not x in other.graph : 
  425.                 retval.add(x)
  426.         return retval
  427.  
  428.     # Conv. methods
  429.  
  430.     def set(self, (subject, predicate, object)):
  431.         """Convenience method to update the value of object
  432.  
  433.         Remove any existing triples for subject and predicate before adding
  434.         (subject, predicate, object).
  435.         """
  436.         self.remove((subject, predicate, None))
  437.         self.add((subject, predicate, object))
  438.  
  439.     def subjects(self, predicate=None, object=None):
  440.         """A generator of subjects with the given predicate and object"""
  441.         for s, p, o in self.triples((None, predicate, object)):
  442.             yield s
  443.  
  444.     def predicates(self, subject=None, object=None):
  445.         """A generator of predicates with the given subject and object"""
  446.         for s, p, o in self.triples((subject, None, object)):
  447.             yield p
  448.  
  449.     def objects(self, subject=None, predicate=None):
  450.         """A generator of objects with the given subject and predicate"""
  451.         for s, p, o in self.triples((subject, predicate, None)):
  452.             yield o
  453.  
  454.     def subject_predicates(self, object=None):
  455.         """A generator of (subject, predicate) tuples for the given object"""
  456.         for s, p, o in self.triples((None, None, object)):
  457.             yield s, p
  458.  
  459.     def subject_objects(self, predicate=None):
  460.         """A generator of (subject, object) tuples for the given predicate"""
  461.         for s, p, o in self.triples((None, predicate, None)):
  462.             yield s, o
  463.  
  464.     def predicate_objects(self, subject=None):
  465.         """A generator of (predicate, object) tuples for the given subject"""
  466.         for s, p, o in self.triples((subject, None, None)):
  467.             yield p, o
  468.  
  469.     def triples_choices(self, (subject, predicate, object_),context=None):
  470.         for (s, p, o), cg in self.store.triples_choices(
  471.             (subject, predicate, object_), context=self):
  472.             yield (s, p, o)
  473.  
  474.     def value(self, subject=None, predicate=RDF.value, object=None,
  475.               default=None, any=True):
  476.         """Get a value for a pair of two criteria
  477.  
  478.         Exactly one of subject, predicate, object must be None. Useful if one
  479.         knows that there may only be one value.
  480.  
  481.         It is one of those situations that occur a lot, hence this
  482.         'macro' like utility
  483.  
  484.         Parameters:
  485.         -----------
  486.         subject, predicate, object  -- exactly one must be None
  487.         default -- value to be returned if no values found
  488.         any -- if True:
  489.                  return any value in the case there is more than one
  490.                else:
  491.                  raise UniquenessError
  492.         """
  493.         retval = default
  494.  
  495.         if (subject is None and predicate is None) or \
  496.                 (subject is None and object is None) or \
  497.                 (predicate is None and object is None):
  498.             return None
  499.         
  500.         if object is None:
  501.             values = self.objects(subject, predicate)
  502.         if subject is None:
  503.             values = self.subjects(predicate, object)
  504.         if predicate is None:
  505.             values = self.predicates(subject, object)
  506.  
  507.         try:
  508.             retval = values.next()
  509.         except StopIteration, e:
  510.             retval = default
  511.         else:
  512.             if any is False:
  513.                 try:
  514.                     next = values.next()
  515.                     msg = ("While trying to find a value for (%s, %s, %s) the "
  516.                            "following multiple values where found:\n" %
  517.                            (subject, predicate, object))
  518.                     triples = self.store.triples((subject, predicate, object), None)
  519.                     for (s, p, o), contexts in triples:
  520.                         msg += "(%s, %s, %s)\n (contexts: %s)\n" % (
  521.                             s, p, o, list(contexts))
  522.                     raise exceptions.UniquenessError(msg)
  523.                 except StopIteration, e:
  524.                     pass
  525.         return retval
  526.  
  527.     def label(self, subject, default=''):
  528.         """Query for the RDFS.label of the subject
  529.  
  530.         Return default if no label exists
  531.         """
  532.         if subject is None:
  533.             return default
  534.         return self.value(subject, RDFS.label, default=default, any=True)
  535.  
  536.     def comment(self, subject, default=''):
  537.         """Query for the RDFS.comment of the subject
  538.  
  539.         Return default if no comment exists
  540.         """
  541.         if subject is None:
  542.             return default
  543.         return self.value(subject, RDFS.comment, default=default, any=True)
  544.  
  545.     def items(self, list):
  546.         """Generator over all items in the resource specified by list
  547.  
  548.         list is an RDF collection.
  549.         """
  550.         while list:
  551.             item = self.value(list, RDF.first)
  552.             if item:
  553.                 yield item
  554.             list = self.value(list, RDF.rest)
  555.  
  556.     def transitive_objects(self, subject, property, remember=None):
  557.         """Transitively generate objects for the `property` relationship
  558.  
  559.         Generated objects belong to the depth first transitive closure of the
  560.         `property` relationship starting at `subject`.
  561.         """
  562.         if remember is None:
  563.             remember = {}
  564.         if subject in remember:
  565.             return
  566.         remember[subject] = 1
  567.         yield subject
  568.         for object in self.objects(subject, property):
  569.             for o in self.transitive_objects(object, property, remember):
  570.                 yield o
  571.  
  572.     def transitive_subjects(self, predicate, object, remember=None):
  573.         """Transitively generate objects for the `property` relationship
  574.  
  575.         Generated objects belong to the depth first transitive closure of the
  576.         `property` relationship starting at `subject`.
  577.         """
  578.         if remember is None:
  579.             remember = {}
  580.         if object in remember:
  581.             return
  582.         remember[object] = 1
  583.         yield object
  584.         for subject in self.subjects(predicate, object):
  585.             for s in self.transitive_subjects(predicate, subject, remember):
  586.                 yield s
  587.  
  588.     def seq(self, subject):
  589.         """Check if subject is an rdf:Seq
  590.  
  591.         If yes, it returns a Seq class instance, None otherwise.
  592.         """
  593.         if (subject, RDF.type, RDF.Seq) in self:
  594.             return Seq(self, subject)
  595.         else:
  596.             return None
  597.  
  598.     def qname(self, uri):
  599.         return self.namespace_manager.qname(uri)
  600.  
  601.     def compute_qname(self, uri):
  602.         return self.namespace_manager.compute_qname(uri)
  603.  
  604.     def bind(self, prefix, namespace, override=True):
  605.         """Bind prefix to namespace
  606.  
  607.         If override is True will bind namespace to given prefix if namespace
  608.         was already bound to a different prefix.
  609.         """
  610.         return self.namespace_manager.bind(prefix, namespace, override=override)
  611.  
  612.     def namespaces(self):
  613.         """Generator over all the prefix, namespace tuples"""
  614.         for prefix, namespace in self.namespace_manager.namespaces():
  615.             yield prefix, namespace
  616.  
  617.     def absolutize(self, uri, defrag=1):
  618.         """Turn uri into an absolute URI if it's not one already"""
  619.         return self.namespace_manager.absolutize(uri, defrag)
  620.  
  621.     def serialize(self, destination=None, format="xml", base=None, encoding=None, **args):
  622.         """Serialize the Graph to destination
  623.  
  624.         If destination is None serialize method returns the serialization as a
  625.         string. Format defaults to xml (AKA rdf/xml).
  626.         """
  627.         serializer = plugin.get(format, Serializer)(self)
  628.         return serializer.serialize(destination, base=base, encoding=encoding, **args)
  629.  
  630.     def prepare_input_source(self, source, publicID=None):
  631.         if isinstance(source, InputSource):
  632.             input_source = source
  633.         else:
  634.             if hasattr(source, "read") and not isinstance(source, Namespace):
  635.                 # we need to make sure it's not an instance of Namespace since
  636.                 # Namespace instances have a read attr
  637.                 input_source = prepare_input_source(source)
  638.             else:
  639.                 location = self.absolutize(source)
  640.                 input_source = URLInputSource(location)
  641.                 publicID = publicID or location
  642.         if publicID:
  643.             input_source.setPublicId(publicID)
  644.         id = input_source.getPublicId()
  645.         if id is None:
  646.             #_logger.warning("no publicID set for source. Using '' for publicID.")
  647.             input_source.setPublicId("")
  648.         return input_source
  649.  
  650.     def parse(self, source, publicID=None, format="xml", **args):
  651.         """ Parse source into Graph
  652.  
  653.         If Graph is context-aware it'll get loaded into it's own context
  654.         (sub graph). Format defaults to xml (AKA rdf/xml). The publicID
  655.         argument is for specifying the logical URI for the case that it's
  656.         different from the physical source URI. Returns the context into which
  657.         the source was parsed.
  658.         """
  659.         source = self.prepare_input_source(source, publicID)
  660.         parser = plugin.get(format, Parser)()
  661.         parser.parse(source, self, **args)
  662.         return self
  663.  
  664.     def load(self, source, publicID=None, format="xml"):
  665.         self.parse(source, publicID, format)
  666.  
  667.     def query(self, strOrQuery, initBindings={}, initNs={}, DEBUG=False,
  668.               processor="sparql"):
  669.         """
  670.         Executes a SPARQL query (eventually will support Versa queries with same method) against this Graph
  671.         strOrQuery - Is either a string consisting of the SPARQL query or an instance of rdflib.sparql.bison.Query.Query
  672.         initBindings - A mapping from a Variable to an RDFLib term (used as initial bindings for SPARQL query)
  673.         initNS - A mapping from a namespace prefix to an instance of rdflib.Namespace (used for SPARQL query)
  674.         DEBUG - A boolean flag passed on to the SPARQL parser and evaluation engine
  675.         processor - The kind of RDF query (must be 'sparql' until Versa is ported)
  676.         """
  677.         assert processor == 'sparql',"SPARQL is currently the only supported RDF query language"
  678.         p = plugin.get(processor, sparql.Processor)(self)
  679.         return plugin.get('SPARQLQueryResult',QueryResult)(p.query(strOrQuery, initBindings, initNs, DEBUG))
  680.  
  681.         processor_plugin = plugin.get(processor, sparql.Processor)(self.store)
  682.         qresult_plugin = plugin.get('SPARQLQueryResult', QueryResult)
  683.  
  684.         res = processor_plugin.query(strOrQuery, initBindings, initNs, DEBUG)
  685.         return qresult_plugin(res)
  686.  
  687.     def n3(self):
  688.         """return an n3 identifier for the Graph"""
  689.         return "[%s]" % self.identifier.n3()
  690.  
  691.     def __reduce__(self):
  692.         return (Graph, (self.store, self.identifier,))
  693.  
  694.     def isomorphic(self, other):
  695.         # TODO: this is only an approximation.
  696.         if len(self) != len(other):
  697.             return False
  698.         for s, p, o in self:
  699.             if not isinstance(s, BNode) and not isinstance(o, BNode):
  700.                 if not (s, p, o) in other:
  701.                     return False
  702.         for s, p, o in other:
  703.             if not isinstance(s, BNode) and not isinstance(o, BNode):
  704.                 if not (s, p, o) in self:
  705.                     return False
  706.         # TODO: very well could be a false positive at this point yet.
  707.         return True
  708.  
  709.     def connected(self):
  710.         """Check if the Graph is connected
  711.  
  712.         The Graph is considered undirectional.
  713.  
  714.         Performs a search on the Graph, starting from a random node. Then
  715.         iteratively goes depth-first through the triplets where the node is
  716.         subject and object. Return True if all nodes have been visited and
  717.         False if it cannot continue and there are still unvisited nodes left.
  718.         """
  719.         all_nodes = list(self.all_nodes())
  720.         discovered = []
  721.  
  722.         # take a random one, could also always take the first one, doesn't
  723.         # really matter.
  724.         visiting = [all_nodes[random.randrange(len(all_nodes))]]
  725.         while visiting:
  726.             x = visiting.pop()
  727.             if x not in discovered:
  728.                 discovered.append(x)
  729.             for new_x in self.objects(subject=x):
  730.                 if new_x not in discovered and new_x not in visiting:
  731.                     visiting.append(new_x)
  732.             for new_x in self.subjects(object=x):
  733.                 if new_x not in discovered and new_x not in visiting:
  734.                     visiting.append(new_x)
  735.  
  736.         # optimisation by only considering length, since no new objects can
  737.         # be introduced anywhere.
  738.         if len(all_nodes) == len(discovered):
  739.             return True
  740.         else:
  741.             return False
  742.  
  743.     def all_nodes(self):
  744.         obj = set(self.objects())
  745.         allNodes = obj.union(set(self.subjects()))
  746.         return allNodes
  747.  
  748.  
  749. class ConjunctiveGraph(Graph):
  750.  
  751.     def __init__(self, store='default', identifier=None):
  752.         super(ConjunctiveGraph, self).__init__(store)
  753.         assert self.store.context_aware, ("ConjunctiveGraph must be backed by"
  754.                                           " a context aware store.")
  755.         self.context_aware = True
  756.         self.default_context = Graph(store=self.store,
  757.                                      identifier=identifier or BNode())
  758.  
  759.     def __str__(self):
  760.         pattern = ("[a rdflib:ConjunctiveGraph;rdflib:storage "
  761.                    "[a rdflib:Store;rdfs:label '%s']]")
  762.         return pattern % self.store.__class__.__name__
  763.  
  764.     def add(self, (s, p, o)):
  765.         """Add the triple to the default context"""
  766.         self.store.add((s, p, o), context=self.default_context, quoted=False)
  767.  
  768.     def addN(self, quads):
  769.         """Add a sequence of triple with context"""
  770.         self.store.addN(quads)
  771.  
  772.     def remove(self, (s, p, o)):
  773.         """Removes from all its contexts"""
  774.         self.store.remove((s, p, o), context=None)
  775.  
  776.     def triples(self, (s, p, o)):
  777.         """Iterate over all the triples in the entire conjunctive graph"""
  778.         for (s, p, o), cg in self.store.triples((s, p, o), context=None):
  779.             yield s, p, o
  780.  
  781.     def quads(self,(s,p,o)):
  782.         """Iterate over all the quads in the entire conjunctive graph"""
  783.         for (s, p, o), cg in self.store.triples((s, p, o), context=None):
  784.             for ctx in cg:
  785.                 yield s, p, o, ctx
  786.             
  787.     def triples_choices(self, (s, p, o)):
  788.         """Iterate over all the triples in the entire conjunctive graph"""
  789.         for (s1, p1, o1), cg in self.store.triples_choices((s, p, o),
  790.                                                            context=None):
  791.             yield (s1, p1, o1)
  792.  
  793.     def __len__(self):
  794.         """Number of triples in the entire conjunctive graph"""
  795.         return self.store.__len__()
  796.  
  797.     def contexts(self, triple=None):
  798.         """Iterate over all contexts in the graph
  799.  
  800.         If triple is specified, iterate over all contexts the triple is in.
  801.         """
  802.         for context in self.store.contexts(triple):
  803.             yield context
  804.  
  805.     def remove_context(self, context):
  806.         """Removes the given context from the graph"""
  807.         self.store.remove((None, None, None), context)
  808.  
  809.     def context_id(self, uri, context_id=None):
  810.         """URI#context"""
  811.         uri = uri.split("#", 1)[0]
  812.         if context_id is None:
  813.             context_id = "#context"
  814.         return URIRef(context_id, base=uri)
  815.  
  816.     def parse(self, source, publicID=None, format="xml", **args):
  817.         """Parse source into Graph into it's own context (sub graph)
  818.  
  819.         Format defaults to xml (AKA rdf/xml). The publicID argument is for
  820.         specifying the logical URI for the case that it's different from the
  821.         physical source URI. Returns the context into which the source was
  822.         parsed. In the case of n3 it returns the root context.
  823.         """
  824.         source = self.prepare_input_source(source, publicID)
  825.         id = self.context_id(self.absolutize(source.getPublicId()))
  826.         context = Graph(store=self.store, identifier=id)
  827.         context.remove((None, None, None))
  828.         context.parse(source, publicID=publicID, format=format, **args)
  829.         return context
  830.  
  831.     def __reduce__(self):
  832.         return (ConjunctiveGraph, (self.store, self.identifier))
  833.  
  834.  
  835. class QuotedGraph(Graph):
  836.  
  837.     def __init__(self, store, identifier):
  838.         super(QuotedGraph, self).__init__(store, identifier)
  839.  
  840.     def add(self, triple):
  841.         """Add a triple with self as context"""
  842.         self.store.add(triple, self, quoted=True)
  843.  
  844.     def addN(self,quads):
  845.         """Add a sequence of triple with context"""
  846.         self.store.addN([(s,p,o,c) for s,p,o,c in quads
  847.                                    if isinstance(c, QuotedGraph)
  848.                                    and c.identifier is self.identifier])
  849.  
  850.     def n3(self):
  851.         """Return an n3 identifier for the Graph"""
  852.         return "{%s}" % self.identifier.n3()
  853.  
  854.     def __str__(self):
  855.         identifier = self.identifier.n3()
  856.         label = self.store.__class__.__name__
  857.         pattern = ("{this rdflib.identifier %s;rdflib:storage "
  858.                    "[a rdflib:Store;rdfs:label '%s']}")
  859.         return pattern % (identifier, label)
  860.  
  861.     def __reduce__(self):
  862.         return (QuotedGraph, (self.store, self.identifier))
  863.  
  864.  
  865. class GraphValue(QuotedGraph):
  866.     def __init__(self, store, identifier=None, graph=None):
  867.         if graph is not None:
  868.             assert identifier is None
  869.             np = store.node_pickler
  870.             identifier = md5()
  871.             s = list(graph.triples((None, None, None)))
  872.             s.sort()
  873.             for t in s:
  874.                 identifier.update("^".join((np.dumps(i) for i in t)))
  875.             identifier = URIRef("data:%s" % identifier.hexdigest())
  876.             super(GraphValue, self).__init__(store, identifier)
  877.             for t in graph:
  878.                 store.add(t, context=self)
  879.         else:
  880.             super(GraphValue, self).__init__(store, identifier)
  881.  
  882.  
  883.     def add(self, triple):
  884.         raise Exception("not mutable")
  885.  
  886.     def remove(self, triple):
  887.         raise Exception("not mutable")
  888.  
  889.     def __reduce__(self):
  890.         return (GraphValue, (self.store, self.identifier,))
  891.  
  892.  
  893. class Seq(object):
  894.     """Wrapper around an RDF Seq resource
  895.  
  896.     It implements a container type in Python with the order of the items
  897.     returned corresponding to the Seq content. It is based on the natural
  898.     ordering of the predicate names _1, _2, _3, etc, which is the
  899.     'implementation' of a sequence in RDF terms.
  900.     """
  901.  
  902.     def __init__(self, graph, subject):
  903.         """Parameters:
  904.  
  905.         - graph:
  906.             the graph containing the Seq
  907.  
  908.         - subject:
  909.             the subject of a Seq. Note that the init does not
  910.             check whether this is a Seq, this is done in whoever
  911.             creates this instance!
  912.         """
  913.  
  914.         _list = self._list = list()
  915.         LI_INDEX = RDF.RDFNS["_"]
  916.         for (p, o) in graph.predicate_objects(subject):
  917.             if p.startswith(LI_INDEX): #!= RDF.Seq: #
  918.                 i = int(p.replace(LI_INDEX, ''))
  919.                 _list.append((i, o))
  920.  
  921.         # here is the trick: the predicates are _1, _2, _3, etc. Ie,
  922.         # by sorting the keys (by integer) we have what we want!
  923.         _list.sort()
  924.  
  925.     def __iter__(self):
  926.         """Generator over the items in the Seq"""
  927.         for _, item in self._list:
  928.             yield item
  929.  
  930.     def __len__(self):
  931.         """Length of the Seq"""
  932.         return len(self._list)
  933.  
  934.     def __getitem__(self, index):
  935.         """Item given by index from the Seq"""
  936.         index, item = self._list.__getitem__(index)
  937.         return item
  938.  
  939.  
  940. class BackwardCompatGraph(ConjunctiveGraph):
  941.  
  942.     def __init__(self, backend='default'):
  943.         warnings.warn("Use ConjunctiveGraph instead. "
  944.                       "( from rdflib.Graph import ConjunctiveGraph )",
  945.                       DeprecationWarning, stacklevel=2)
  946.         super(BackwardCompatGraph, self).__init__(store=backend)
  947.  
  948.     def __get_backend(self):
  949.         return self.store
  950.     backend = property(__get_backend)
  951.  
  952.     def open(self, configuration, create=True):
  953.         return ConjunctiveGraph.open(self, configuration, create)
  954.  
  955.     def add(self, (s, p, o), context=None):
  956.         """Add to to the given context or to the default context"""
  957.         if context is not None:
  958.             c = self.get_context(context)
  959.             assert c.identifier == context, "%s != %s" % (c.identifier, context)
  960.         else:
  961.             c = self.default_context
  962.         self.store.add((s, p, o), context=c, quoted=False)
  963.  
  964.     def remove(self, (s, p, o), context=None):
  965.         """Remove from the given context or from the default context"""
  966.         if context is not None:
  967.             context = self.get_context(context)
  968.         self.store.remove((s, p, o), context)
  969.  
  970.     def triples(self, (s, p, o), context=None):
  971.         """Iterate over all the triples in the entire graph"""
  972.         if context is not None:
  973.             c = self.get_context(context)
  974.             assert c.identifier == context
  975.         else:
  976.             c = None
  977.         for (s, p, o), cg in self.store.triples((s, p, o), c):
  978.             yield (s, p, o)
  979.  
  980.     def __len__(self, context=None):
  981.         """Number of triples in the entire graph"""
  982.         if context is not None:
  983.             context = self.get_context(context)
  984.         return self.store.__len__(context)
  985.  
  986.     def get_context(self, identifier, quoted=False):
  987.         """Return a context graph for the given identifier
  988.  
  989.         identifier must be a URIRef or BNode.
  990.         """
  991.         assert isinstance(identifier, URIRef) or \
  992.                isinstance(identifier, BNode), type(identifier)
  993.         if quoted:
  994.             assert False
  995.             return QuotedGraph(self.store, identifier)
  996.             #return QuotedGraph(self.store, Graph(store=self.store,
  997.             #                                     identifier=identifier))
  998.         else:
  999.             return Graph(store=self.store, identifier=identifier,
  1000.                          namespace_manager=self)
  1001.             #return Graph(self.store, Graph(store=self.store,
  1002.             #                               identifier=identifier))
  1003.  
  1004.     def remove_context(self, context):
  1005.         """Remove the given context from the graph"""
  1006.         self.store.remove((None, None, None), self.get_context(context))
  1007.  
  1008.     def contexts(self, triple=None):
  1009.         """Iterate over all contexts in the graph
  1010.  
  1011.         If triple is specified, iterate over all contexts the triple is in.
  1012.         """
  1013.         for context in self.store.contexts(triple):
  1014.             yield context.identifier
  1015.  
  1016.     def subjects(self, predicate=None, object=None, context=None):
  1017.         """Generate subjects with the given predicate and object"""
  1018.         for s, p, o in self.triples((None, predicate, object), context):
  1019.             yield s
  1020.  
  1021.     def predicates(self, subject=None, object=None, context=None):
  1022.         """Generate predicates with the given subject and object"""
  1023.         for s, p, o in self.triples((subject, None, object), context):
  1024.             yield p
  1025.  
  1026.     def objects(self, subject=None, predicate=None, context=None):
  1027.         """Generate objects with the given subject and predicate"""
  1028.         for s, p, o in self.triples((subject, predicate, None), context):
  1029.             yield o
  1030.  
  1031.     def subject_predicates(self, object=None, context=None):
  1032.         """Generate (subject, predicate) tuples for the given object"""
  1033.         for s, p, o in self.triples((None, None, object), context):
  1034.             yield s, p
  1035.  
  1036.     def subject_objects(self, predicate=None, context=None):
  1037.         """Generate (subject, object) tuples for the given predicate"""
  1038.         for s, p, o in self.triples((None, predicate, None), context):
  1039.             yield s, o
  1040.  
  1041.     def predicate_objects(self, subject=None, context=None):
  1042.         """Generate (predicate, object) tuples for the given subject"""
  1043.         for s, p, o in self.triples((subject, None, None), context):
  1044.             yield p, o
  1045.  
  1046.     def __reduce__(self):
  1047.         return (BackwardCompatGraph, (self.store, self.identifier))
  1048.  
  1049.     def save(self, destination, format="xml", base=None, encoding=None):
  1050.         warnings.warn("Use serialize method instead. ",
  1051.                       DeprecationWarning, stacklevel=2)
  1052.         self.serialize(destination=destination, format=format, base=base,
  1053.                        encoding=encoding)
  1054.  
  1055. class ModificationException(Exception):
  1056.  
  1057.     def __init__(self):
  1058.         pass
  1059.  
  1060.     def __str__(self):
  1061.         return ("Modifications and transactional operations not allowed on "
  1062.                 "ReadOnlyGraphAggregate instances")
  1063.  
  1064. class UnSupportedAggregateOperation(Exception):
  1065.  
  1066.     def __init__(self):
  1067.         pass
  1068.  
  1069.     def __str__(self):
  1070.         return ("This operation is not supported by ReadOnlyGraphAggregate "
  1071.                 "instances")
  1072.  
  1073. class ReadOnlyGraphAggregate(ConjunctiveGraph):
  1074.     """Utility class for treating a set of graphs as a single graph
  1075.  
  1076.     Only read operations are supported (hence the name). Essentially a
  1077.     ConjunctiveGraph over an explicit subset of the entire store.
  1078.     """
  1079.  
  1080.     def __init__(self, graphs,store='default'):
  1081.         if store is not None:
  1082.             super(ReadOnlyGraphAggregate, self).__init__(store)
  1083.         assert isinstance(graphs, list) and graphs\
  1084.                and [g for g in graphs if isinstance(g, Graph)],\
  1085.                "graphs argument must be a list of Graphs!!"
  1086.         self.graphs = graphs
  1087.  
  1088.     def __repr__(self):
  1089.         return "<ReadOnlyGraphAggregate: %s graphs>" % len(self.graphs)
  1090.  
  1091.     def destroy(self, configuration):
  1092.         raise ModificationException()
  1093.  
  1094.     #Transactional interfaces (optional)
  1095.     def commit(self):
  1096.         raise ModificationException()
  1097.  
  1098.     def rollback(self):
  1099.         raise ModificationException()
  1100.  
  1101.     def open(self, configuration, create=False):
  1102.         # TODO: is there a use case for this method?
  1103.         for graph in self.graphs:
  1104.             graph.open(self, configuration, create)
  1105.  
  1106.     def close(self):
  1107.         for graph in self.graphs:
  1108.             graph.close()
  1109.  
  1110.     def add(self, (s, p, o)):
  1111.         raise ModificationException()
  1112.  
  1113.     def addN(self, quads):
  1114.         raise ModificationException()
  1115.  
  1116.     def remove(self, (s, p, o)):
  1117.         raise ModificationException()
  1118.  
  1119.     def triples(self, (s, p, o)):
  1120.         for graph in self.graphs:
  1121.             for s1, p1, o1 in graph.triples((s, p, o)):
  1122.                 yield (s1, p1, o1)
  1123.  
  1124.     def quads(self,(s,p,o)):
  1125.         """Iterate over all the quads in the entire aggregate graph"""
  1126.         for graph in self.graphs:
  1127.             for s1, p1, o1 in graph.triples((s, p, o)):
  1128.                 yield (s1, p1, o1, graph)
  1129.  
  1130.     def __len__(self):
  1131.         return reduce(lambda x, y: x + y, [len(g) for g in self.graphs])
  1132.  
  1133.     def __hash__(self):
  1134.         raise UnSupportedAggregateOperation()
  1135.  
  1136.     def __cmp__(self, other):
  1137.         if other is None:
  1138.             return -1
  1139.         elif isinstance(other, Graph):
  1140.             return -1
  1141.         elif isinstance(other, ReadOnlyGraphAggregate):
  1142.             return cmp(self.graphs, other.graphs)
  1143.         else:
  1144.             return -1
  1145.  
  1146.     def __iadd__(self, other):
  1147.         raise ModificationException()
  1148.  
  1149.     def __isub__(self, other):
  1150.         raise ModificationException()
  1151.  
  1152.     # Conv. methods
  1153.  
  1154.     def triples_choices(self, (subject, predicate, object_), context=None):
  1155.         for graph in self.graphs:
  1156.             choices = graph.triples_choices((subject, predicate, object_))
  1157.             for (s, p, o) in choices:
  1158.                 yield (s, p, o)
  1159.  
  1160.     def qname(self, uri):
  1161.         raise UnSupportedAggregateOperation()
  1162.  
  1163.     def compute_qname(self, uri):
  1164.         raise UnSupportedAggregateOperation()
  1165.  
  1166.     def bind(self, prefix, namespace, override=True):
  1167.         raise UnSupportedAggregateOperation()
  1168.  
  1169.     def namespaces(self):
  1170.         if hasattr(self,'namespace_manager'):
  1171.             for prefix, namespace in self.namespace_manager.namespaces():
  1172.                 yield prefix, namespace
  1173.         else:
  1174.             for graph in self.graphs:
  1175.                 for prefix, namespace in graph.namespaces():
  1176.                     yield prefix, namespace
  1177.  
  1178.     def absolutize(self, uri, defrag=1):
  1179.         raise UnSupportedAggregateOperation()
  1180.  
  1181.     def parse(self, source, publicID=None, format="xml", **args):
  1182.         raise ModificationException()
  1183.  
  1184.     def n3(self):
  1185.         raise UnSupportedAggregateOperation()
  1186.  
  1187.     def __reduce__(self):
  1188.         raise UnSupportedAggregateOperation()
  1189.  
  1190.  
  1191. def test():
  1192.     import doctest
  1193.     doctest.testmod()
  1194.  
  1195. if __name__ == '__main__':
  1196.     test()
  1197.